package com.code.bolg.service.impl;

import com.code.bolg.bean.Category;
import com.code.bolg.enums.DelFlagEnum;
import com.code.bolg.enums.ResultEnum;
import com.code.bolg.exception.BolgExcetion;
import com.code.bolg.repository.CategoryRepository;
import com.code.bolg.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryRepository categoryRepository;

    @Override
    public Category save(Category category) {
        Category save = categoryRepository.save(category);
        return save;
    }

    @Override
    public int deleteById(int id) {

        Optional<Category> optional=categoryRepository.findById(id);
        if(optional.isPresent()){
            categoryRepository.deleteById(id);
            return 1;
        }else{
            return 0;
        }
    }

    @Override
    public Category findById(int id) {
        Optional<Category> optional = categoryRepository.findById(id);
        if (optional.isPresent()) {
            Category category = optional.get();
            return category;
        } else {
            throw new BolgExcetion(ResultEnum.NOTFINDDATA);
        }
    }

    @Override
    public List<Category> findAll() {
        Category c = new Category();
        c.setFlag(DelFlagEnum.NOTDELETE.getCode());
        Sort sort = new Sort(Sort.Direction.DESC, "updateDate");
        Example<Category>  example =  Example.of(c);        //分页构造
        List<Category> all = categoryRepository.findAll(example,sort);
        return  all;
    }
}
